<template>
  <!-- <div class="login">
    <div class="login-con">
      <Card icon="log-in" title="欢迎登录" :bordered="false">
        <div class="form-con">
          <login-form @on-success-valid="handleSubmit"></login-form>
          <p class="login-tip">输入任意用户名和密码即可</p>
        </div>
      </Card>
    </div>
  </div> -->
  <div class="login" v-if="qywxautologin">
    <!-- @click="homePage" -->
<!--    <header><img src="@/assets/homePage/scrmlogo.png" alt="" /></header>-->
    <div class="loginform">
      <LoginForm
        :loginLoading.sync="loginLoading"
        :gologin="gologin"
        @on-success-valid="handleSubmit"
        @wx-code-success-valid="handleCodeSubmit"
      ></LoginForm>
    </div>
<!--    <div class="bot_text">
      <div class="font14 mb12 colorFFF">
        云之学 — 低成本 高质量 快速为培训机构开展新业务
      </div>
      <div class="font12 colorFFF">
        备案/许可证编号为：豫ICP备20023572号
        <span> </span> 郑州云谋网络科技有限公司 版权所有
      </div>
    </div>-->
  </div>
</template>

<script>
import { newagentConfig } from "@/libs/wwsignname";

import { mapActions } from "vuex";
import LoginForm from "./components/login-form";
import service from "@/libs/service.js";
// import { removeToken } from '@/libs/util.js'
// import { getRouterData } from '../../api/loginApi'
// import { defaultRoute } from '../../router/routers'

// import SmsLogin from './components/SmsLogin'
// import APIS from '../../api'
// import { mapActions } from 'vuex'

export default {
  components: {
    LoginForm,
  },
  data() {
    return {
      loginLoading: false,
      gologin: false,
      qywxautologin: false,
    };
  },
  created() {
    this.getUserInfo().then(res=>{
      console.log(res);
    })
    var code = this.$route.query.code;
    if (this.envjudge() == "com-wx-pc") {
      // newagentConfig()
      this.qywxautologin = false;
      this.$Spin.show();
      if (!code) {
        if (process.env.NODE_ENV === "prerelease") {
          window.location.href =
            "https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww1add0f813968d635&redirect_uri=https%3A%2F%2Fpreshoufei.yzxsaas.com%2F%23%2Floading&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
        } else if (process.env.NODE_ENV === "production") {
          window.location.href =
            "https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww1add0f813968d635&redirect_uri=https%3A%2F%2Fpreshoufei.yzxsaas.com%2F%23%2Floading&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
        }
      } else {
        this.handleCodeSubmitbendi({authCode: code});
      }
      return false;
    } else if (this.envjudge() == "com-wx-mobile") {
      this.qywxautologin = false;
      if (process.env.NODE_ENV === "prerelease") {
        return (window.location.href =
          "https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww1add0f813968d635&redirect_uri=https%3A%2F%2Fpreshoufei.yzxsaas.com%2Fapp%2F&scope=SCOPE&state=STATE#wechat_redirect");
      } else if (process.env.NODE_ENV === "production") {
        return (window.location.href =
          "https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww1add0f813968d635&redirect_uri=https%3A%2F%2Fpreshoufei.yzxsaas.com%2Fapp%2F&scope=SCOPE&state=STATE#wechat_redirect");
      }
    }
    if (code) {
      // 企业微信扫码登录 https://prescrm.yzxsaas.com/#/login?auth_code=LMKyCFw01sAbA8MTOpGRwjRdVh9tNJuS2qGGIC37QSwztJ_03NS_nWf6lH4HTfEu5eZ5cn_srgWFXr8085JW7nrLxcDRfETLW0sVMQEdTuWJCyLHJgxJfNmDulEfZoLJ&appid=ww1add0f813968d635
      // 企业微信授权 https://prescrm.yzxsaas.com/?auth_code=8SKq_CdXev0hMdhtIeN71EtCDjqwJ83wK1GaYJdGIZaTIySJidxkRM5H2I9ffdM-OC3m-ED02kyJppcOY748V_BtPyaW-TL5J_xeuLL0fUw&state=scrmAuth&expires_in=1200#/login
      // 企业微信后台登录 https://prescrm.yzxsaas.com/?auth_code=QL5tHHpqs0VQoYgZcDaH8jeqPM3bsH_4IH5EiDywshueQFI0pS_4f-zHYoY_XXYQH01k7V-B1a7gLXBV32nmbjzVucBNlVs-f2eEPsupVag#/home
      this.qywxautologin = false;
      this.$Spin.show();
      // 企业微信扫码登录
      // 企业微信后台登录进来
      this.handleCodeSubmit(code);
      // if (window.location.href.indexOf("&state=") != -1) {
      //   // 企业微信授权 注册? 并登录
      //   towurl = oneurl[1].split("&state=");
      //   this.SubmitLogin(towurl[0]);
      // }
    } else {
      this.qywxautologin = true;
    }
  },
  methods: {
    ...mapActions([
      "handleLogin",
      "getUserInfo",
      "handlegoLogin",
      "qywxzddl",
      "wxAuthlogin",
    ]),
    handleSubmit({ userPhone, userPassword }) {
      this.handleLogin({ userPhone, userPassword, platformCode: "ym_scrm" })
        .then((resLogin) => {
          this.getUserInfo(resLogin)
            .then((res) => {
              // this.APIS.getRouter({ sd: 1 }).then((routerRes) => {
              //   service.routerRes(routerRes.data);
                this.$router.replace({
                  name: this.$config.homeName,
                });
              // });
            })
            .catch(() => {
              this.loginLoading = false;
            });
        })
        .catch(() => {
          this.loginLoading = false;
        });
    },
    SubmitLogin(urlcode) {
      let url = location.search; //获取url中"?"符后的字串
      if (url) {
        let urls = url.split("?");
        let theRequest = urls[1].split("#");
        this.authCode = theRequest[0].split("&");
        this.authCode.forEach((item) => {
          if (item.indexOf("auth_code=" || "code") === 0) {
            this.preAuthCode = item.split("=")[1];
          }
          if (item.indexOf("state=") === 0) {
            this.state = item.split("=")[1];
          }
          if (item.indexOf("expires_in=") === 0) {
            this.expiresIn = item.split("=")[1];
          }
        });
        this.$Spin.hide();
        if (this.preAuthCode && this.state && this.expiresIn) {
          this.wxAuthlogin({
            preAuthCode: this.preAuthCode,
            expiresIn: this.expiresIn,
            state: this.state,
          })
            .then((resLogin) => {
              if (resLogin.code === 20000) {
                this.$Message.success("授权添加应用成功");
                localStorage.setItem(
                  "ifaccountyesnoQYWX",
                  resLogin.data.thirdType
                );
                this.$store.commit("print/setPrint", {
                  //print 表示vuex的文件名
                  ifaccountyesnoQYWX:
                    localStorage.getItem("ifaccountyesnoQYWX"),
                });
                this.getUserInfo(resLogin)
                  .then((res) => {
                    // 获取角色路由
                    this.APIS.getMenuList()
                      .then((res) => {
                        console.log('ll', res);
                        // service.routerRes(res.data);
                        this.$router.replace({
                          name: this.$config.homeName,
                        });
                        localStorage.setItem("menus", this.$config.homeName);
                        this.loginLoading = false;
                      })
                      .catch((err) => {
                        this.loginLoading = false;
                        removeToken();
                        console.log(err);
                      });
                  })
                  .catch(() => {
                    this.loginLoading = false;
                  });
              } else {
                this.loginLoading = false;
              }
            })
            .catch(() => {
              this.loginLoading = false;
              // this.$router.push({
              //   name: this.$config.homeName
              // })
            });
        } else if (this.preAuthCode) {
          this.handlegoLogin({
            authCode: this.preAuthCode,
          })
            .then((resLogin) => {
              if (resLogin.code === 20000) {
                localStorage.setItem(
                  "ifaccountyesnoQYWX",
                  resLogin.data.thirdType
                );
                this.$store.commit("print/setPrint", {
                  //print 表示vuex的文件名
                  ifaccountyesnoQYWX:
                    localStorage.getItem("ifaccountyesnoQYWX"),
                });
                this.getUserInfo(resLogin)
                  .then((res) => {
                    // 获取角色路由
                    this.APIS.getMenuList()
                      .then((res) => {
                        console.log('ll', res);
                        // service.routerRes(res.data);
                        this.$router.replace({
                          name: this.$config.homeName,
                        });
                        localStorage.setItem("menus", this.$config.homeName);
                        this.loginLoading = false;
                      })
                      .catch((err) => {
                        this.loginLoading = false;
                        removeToken();
                        console.log(err);
                      });
                  })
                  .catch(() => {
                    this.loginLoading = false;
                  });
              } else {
                this.loginLoading = false;
              }
            })
            .catch(() => {
              this.loginLoading = false;
              // this.$router.push({
              //   name: this.$config.homeName
              // })
            });
        }
      }
      // if(top != self){
      //   top.location=self.location;
      // }else{
      //   var thisurl = location.search;
      //   if(thisurl){
      //     var old_url = window.location.href;
      //     var new_url = old_url.substring(0, old_url.indexOf('?'));
      //     self.location = new_url;
      //   }
      // }
    },
    // 扫码登录
    handleCodeSubmit(data) {
      if (data) {
        this.handlegoLogin({
          authCode: data,
        })
          .then((resLogin) => {
            if (resLogin.code === 20000) {
              if(resLogin.data && resLogin.data.thirdType) {
                localStorage.setItem(
                  "ifaccountyesnoQYWX",
                  resLogin.data.thirdType
                );
              }
              this.$store.commit("print/setPrint", {
                ifaccountyesnoQYWX: localStorage.getItem("ifaccountyesnoQYWX"),
              });
              this.getUserInfo(resLogin)
                .then((res) => {
                  // 获取角色路由
                  this.APIS.getMenuList()
                    .then((res) => {
                      // service.routerRes(res.data);
                      this.$Spin.hide();
                      this.$router.replace({
                        name: this.$config.homeName,
                      });
                      localStorage.setItem("menus", this.$config.homeName);
                      this.loginLoading = false;
                    })
                    .catch((err) => {
                      this.loginLoading = false;
                      removeToken();
                    });
                })
                .catch(() => {
                  this.loginLoading = false;
                });
            } else {
              this.loginLoading = false;
            }
          })
          .catch(() => {
            this.loginLoading = false;
            this.qywxautologin = true;
            this.$Spin.hide();
            // this.$router.push({
            //   name: this.$config.homeName
            // })
          });
      }
      // if(top != self){
      //   top.location=self.location;
      // }else{
      //   var url = location.search;
      //   if(url){
      //     var old_url = window.location.href;
      //     var new_url = old_url.substring(0, old_url.indexOf('?'));
      //     self.location = new_url;
      //   }
      // }
    },
    //
    envjudge() {
      var isMobile = window.navigator.userAgent.match(
        /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
      ); // 是否手机端
      var isWx = /micromessenger/i.test(navigator.userAgent); // 是否微信
      var isComWx = /wxwork/i.test(navigator.userAgent); // 是否企业微信
      if (isComWx && isMobile) {
        //手机端企业微信
        return "com-wx-mobile";
      } else if (isComWx && !isMobile) {
        //PC端企业微信
        return "com-wx-pc";
      } else if (isWx && isMobile) {
        // 手机端微信
        return "wx-mobile";
      } else if (isWx && !isMobile) {
        // PC端微信
        return "wx-pc";
      } else {
        // PC端
        return "other";
      }
    },
    // 企业微信客户端登入scrm触发
    handleCodeSubmitbendi(data) {
      if (data) {
        this.qywxzddl({code: data.authCode})
          .then((resLogin) => {
            if (resLogin.code === 20000) {
              localStorage.setItem(
                "ifaccountyesnoQYWX",
                resLogin.data.thirdType
              );
              this.$store.commit("print/setPrint", {
                ifaccountyesnoQYWX: localStorage.getItem("ifaccountyesnoQYWX"),
              });
              this.getUserInfo(resLogin)
                .then((res) => {
                  // 获取角色路由
                  this.APIS.getMenuList()
                    .then((res) => {
                      // service.routerRes(res.data);
                      this.$router.replace({
                        path: this.$config.homeName,
                      });
                      localStorage.setItem("menus", this.$config.homeName);
                      this.$Spin.hide();
                      this.loginLoading = false;
                      this.gologin = true;
                    })
                    .catch((err) => {
                      this.loginLoading = false;
                      removeToken();
                    });
                })
                .catch(() => {
                  this.loginLoading = false;
                });
            } else {
              this.loginLoading = false;
            }
          })
          .catch((catchres) => {
            this.loginLoading = false;
          });
      }
    },
  },
};
</script>

<style lang="less">
@import "./login.less";
.demo-spin-icon-load {
  animation: ani-demo-spin 1s linear infinite;
}
</style>
